﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Purchase_Order : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        private const int ItemsPerRequest = 10;
        CommandControl cmdFac = new CommandControl();
        IBLLMasterContact bllContact = new MasterContactBLL();
        PurchaseOrderBLL bllPurchaseOrder = new PurchaseOrderBLL();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        PurchaseOrderInstallmentItemBLL bllPoInstalmentItem = new PurchaseOrderInstallmentItemBLL();
        IBLLMasterCommitteeFunction bllComFunction = new MasterCommitteeFunctionBLL();
        IBLLMasterCommitteePosition bllComPosition = new MasterCommitteePositionBLL();
        PurchaseOrderCommitteeBLL bllPoCommittee = new PurchaseOrderCommitteeBLL();
        SysPenaltyCountBLL bllPenaltyCount = new SysPenaltyCountBLL();
        SysPenaltyRateTypeBLL bllPenaltyRateType = new SysPenaltyRateTypeBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        PurchaseOrderPenaltyBLL bllPoPenalty = new PurchaseOrderPenaltyBLL();
        IBLLDocument bllPoFile = new DocumentBLL();
        SysReportBLL bllReport = new SysReportBLL();
        double totalExvat = 0;
        double totalVat = 0;
        double totalAmount = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadPenaltyCount();
                LoadPenaltyRateType(); 
                LoadCommitteePosition();
                LoadCommitteeFunction(); 
                LoadDurationType();
                GetContactDetail();
                GetPoDetail();
                TipConfirm.TargetControls.Add(btnConfirm.ClientID, true);
                tipCommitteeHistory.TargetControls.Add(History_Committee.ClientID, true);
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
                panelLeast.Attributes.Add("style", "visibility:hidden");
                rdbDuration.Attributes.Add("onclick", "return ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                rdbDate.Attributes.Add("onclick", "return ChangeDateRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
            }

            if (rdbDate.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:hidden");
                panelDateReq.Attributes.Add("style", "visibility:visible");
                panelDateReqPick.Attributes.Add("style", "visibility:visible");
            }
            if (rdbDuration.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:visible");
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
            }
        }

        public void RefreshDisplay()
        {
            RadManager1.ResponseScripts.Add(@"CloseActiveToolTip();");
        }

        protected int GetPoSeq()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            return seq;
        }

        protected void Alert()
        {
            RadManager1.Alert(Session["Alert"].ToString());
        }

        protected void OnAjaxUpdate(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip(string elementID, UpdatePanel panel)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Order_Confirm.ascx");
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Order_Confirm)ctrl).RefreshParentDisplay = new CallBackHandle(RefreshDisplay);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Order_Confirm)ctrl).GetPoSeq = new CallBackHandleReturnInt(GetPoSeq);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Order_Confirm)ctrl).Alert = new CallBackHandleAlert(Alert);
            if (Session["SecondLoad"] != "1")
            {
                Session["FirstLoad"] = "1";
            }
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (RadTabStrip1.SelectedTab.Value == "Detail")
            {
                GetPoDetail();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Item")
            {
                LoadGridItem();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Committee")
            {
                LoadGridCommittee();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Penalty")
            {
                LoadGridPenalty();
            }
            else if (RadTabStrip1.SelectedTab.Value == "File")
            {
                LoadGridFile();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Report")
            {
                LoadGrid_Report();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Progress")
            {
                LoadGridApprove();
                LoadGridInform();
                LoadGridRequest();
                LoadGridPublishing();
                LoadGridCommand();
                LoadGridCheck();
            }
        }

        private void btnDeny_Click(object sender, EventArgs e)
        {
            try
            {
                bllPurchaseOrder.UpdatePurchaseOrderStatus(GetPoSeq(), SystemInfo._CancelRecordStatus);
                RadManager1.ResponseScripts.Add(@"CloseWindow();");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
            }
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            string[] TmpArgument = e.Argument.Split(':');

            if (TmpArgument[0] == "SeqCommitteeClick")
            {
                LoadEditCommittee(Convert.ToInt32(TmpArgument[1]));
            }
            if (TmpArgument[0] == "SeqPenaltyClick")
            {
                LoadEditPenalty(Convert.ToInt32(TmpArgument[1]));
            }
            if (TmpArgument[0] == "ReportPdfClick")
            {
                RadManager1.ResponseScripts.Add(@"OpenReport('" + TmpArgument[1] + "','" + GetPoSeq() + "','pdf');");
            }
            if (TmpArgument[0] == "ReportWordClick")
            {
                RadManager1.ResponseScripts.Add(@"OpenReport('" + TmpArgument[1] + "','" + GetPoSeq() + "','word');");
            }
            if (TmpArgument[0] == "ReportExcelClick")
            {
                RadManager1.ResponseScripts.Add(@"OpenReport('" + TmpArgument[1] + "','" + GetPoSeq() + "','excel');");
            }
        }

        protected void ManageDisplay(string Status)
        {
            switch (Status)
            {
                case "A":
                case "P":
                    panelCommand_Detail.Visible = false;
                    panelCommand_Committee.Visible = false;
                    panelCommand_Penalty.Visible = false;
                    panelCommand_File.Visible = false;
                    btnConfirm.Visible = false;
                    btnDeny.Visible = true;
                    break;
                case "C":
                    panelCommand_Detail.Visible = false;
                    panelCommand_Committee.Visible = false;
                    panelCommand_Penalty.Visible = false;
                    panelCommand_File.Visible = false;
                    btnConfirm.Visible = false;
                    btnDeny.Visible = false;
                    break;
                case "N":
                case "R":
                case "W":
                    panelCommand_Detail.Visible = true;
                    panelCommand_Committee.Visible = true;
                    panelCommand_Penalty.Visible = true;
                    panelCommand_File.Visible = true;
                    btnConfirm.Visible = true;
                    btnDeny.Visible = false;
                    break;
            }
        }

        //-----------------------------------------------------------------------------------------------

        #region tab ข้อมูลหลัก

        protected void LoadDurationType()
        {
            IList<SysDurationTypeInfo> infoList = bllDurationType.GetSysDurationType();
            cbDurationType.DataSource = infoList;
            cbDurationType.DataBind();
        }

        protected void GetContactDetail()
        {
            int PoSeq = GetPoSeq();
            MasterContactInfo info = bllContact.GetContactByPo(PoSeq);
            if (info != null)
            {
                lblGfmisCode.Text = info.Gfmis_code;
                lblContactGroup.Text = info.InfoGroup.Name;
                lblNameTh.Text = info.Name_th + (info.Name_eng.Length > 0 ? "(" + info.Name_eng + ")" : "");
                lblAddress.Text = info.All_address;
                lblTel.Text = info.Tel;
                lblEmail.Text = info.Email;
            }
        }

        protected void GetPoDetail()
        {
            PurchaseOrderInfo info = bllPurchaseOrder.GetPurchaseOrderDetail(GetPoSeq());

            txtDate.Text = ((DateTime)info.Date).ToString("dd/MM/yyyy");
            txtName.Text = info.Name;
            txtDurationReq.Text = info.RequireDuration.ToString();
            cbDurationType.SelectedValue = info.InfoDurationType.Seq.ToString();
            cbDurationType.Text = info.InfoDurationType.Name;
            txtDescr.Text = info.Descr;
            if (info.RequireDuration != null)
            {
                lblDuration.Text = "ภายใน " + info.RequireDuration + " " + info.InfoDurationType.Name + " นับจากวันที่รับใบสั่ง";
            }
            else if (info.RequireDate != null)
            {
                lblDuration.Text = "ภายในวันที่ " + ((DateTime)info.RequireDate).ToString("dd/MM/yyyy"); ;
            }
            else
            {
                lblDuration.Text = "";
            }

            if (info.RequireDuration != null)
            {
                rdbDuration.Checked = true;
                rdbDate.Checked = false;
                txtDurationReq.Text = info.RequireDuration.ToString();
                cbDurationType.SelectedValue = info.InfoDurationType.Seq.ToString();
                Session["ReqDuration"] = info.RequireDuration.ToString();
                Session["DurationType"] = cbDurationType.SelectedItem.Text;
                Session["ReqDate"] = "";
            }
            else if (info.RequireDate != null)
            {
                rdbDate.Checked = true;
                rdbDuration.Checked = false;
                txtDateReq.Text = ((DateTime)info.RequireDate).ToString("dd/MM/yyyy");
                Session["ReqDuration"] = "";
                Session["DurationType"] = "";
                Session["ReqDate"] = Convert.ToDateTime(info.RequireDate).ToString("dd/MM/yyyy");
            }

            if (info.RequireDate == null & info.RequireDuration == null)
            {
                rdbDuration.Checked = true;
                rdbDate.Checked = false;
            }

            lblStatus.Text = info.InfoRecordStatus.Name;
            lblProgress.Text = info.InfoProgress.Name;

            cmdFac.ViewCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            cmdFac.SetViewMode(panelDateReqPick);
            cmdFac.SetPanelList(panelDateReqPick, "View");
            cmdFac.SetViewMode(panelDateReq);
            cmdFac.SetPanelList(panelDateReq, "View");
            cmdFac.SetViewMode(panelDuration);
            cmdFac.SetPanelList(panelDuration, "View");
            ManageDisplay(info.InfoRecordStatus.Status);
        }

        protected void Edit_Detail_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            cmdFac.SetPanelList(panelDateReqPick, "Edit");
            cmdFac.SetPanelList(panelDateReq, "Edit");
            cmdFac.SetPanelList(panelDuration, "Edit");
            LoadValiDateDetail();
        }

        protected void EditSave_Detail_Click(object sender, EventArgs e)
        {
            SysDurationTypeInfo infoDurationType = new SysDurationTypeInfo();
            RecordInfo infoRecord = new RecordInfo();
            PurchaseOrderInfo info = new PurchaseOrderInfo();

            info.Seq = GetPoSeq();
            info.Date = Convert.ToDateTime(txtDate.TextWithLiterals);
            info.Name = txtName.Text;
            info.Descr = txtDescr.Text;
            if (rdbDuration.Checked)
            {
                if (txtDurationReq.Text.Length > 0)
                {
                    info.RequireDuration = Convert.ToInt32(txtDurationReq.Value);
                    infoDurationType.Seq = Convert.ToInt32(cbDurationType.SelectedValue);
                }
            }
            if (rdbDate.Checked)
            {
                if (txtDateReq.Text.Length > 0)
                {
                    info.RequireDate = Convert.ToDateTime(txtDateReq.TextWithLiterals);
                }
            }
            infoRecord.Updated_by = 1;
            infoRecord.Updated_when = DateTime.Now;

            info.InfoDurationType = infoDurationType;
            info.InfoRecord = infoRecord;

            try
            {
                bllPurchaseOrder.Update(info);
                GetPoDetail();
                Session["SecondLoad"] = "";
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
            }
        }

        protected void Cancel_Detail_Click(object sender, EventArgs e)
        {
            GetPoDetail();
        }

        private void LoadValiDateDetail()
        {
            RequiredFieldValidator valDate = new RequiredFieldValidator();
            valDate.ID = "ValtxtDate";
            valDate.ControlToValidate = "txtDate";
            valDate.SetFocusOnError = true;
            valDate.Display = ValidatorDisplay.Dynamic;
            valDate.ErrorMessage = "* กรุณาระบุวันที่รายการ *";
            panelValtxtDate.Controls.Add(valDate);
            CustomValidator valCustomDate = new CustomValidator();
            valCustomDate.ID = "ValCustomDate";
            valCustomDate.ControlToValidate = "txtDate";
            valCustomDate.SetFocusOnError = true;
            valCustomDate.Display = ValidatorDisplay.Dynamic;
            valCustomDate.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            valCustomDate.ClientValidationFunction = "validateDate";
            panelValtxtDate.Controls.Add(valCustomDate);
            RequiredFieldValidator valName = new RequiredFieldValidator();
            valName.ID = "ValtxtName";
            valName.ControlToValidate = "txtName";
            valName.SetFocusOnError = true;
            valName.Display = ValidatorDisplay.Dynamic;
            valName.ErrorMessage = "* กรุณาระบุเรื่อง *";
            panelValtxtName.Controls.Add(valName);
            CustomValidator valCustomDateReq = new CustomValidator();
            valCustomDateReq.ID = "ValCustomDateReq";
            valCustomDateReq.ControlToValidate = "txtDateReq";
            valCustomDateReq.SetFocusOnError = true;
            valCustomDateReq.Display = ValidatorDisplay.Dynamic;
            valCustomDateReq.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            valCustomDateReq.ClientValidationFunction = "validateDate";
            panelValDateReq.Controls.Add(valCustomDateReq);
            CustomValidator valCustom = new CustomValidator();
            valCustom.ID = "ValCustom";
            valCustom.SetFocusOnError = true;
            valCustom.Display = ValidatorDisplay.Dynamic;
            valCustom.ErrorMessage = "* กรุณาระบุระยะเวลาส่งมอบ *";
            valCustom.ClientValidationFunction = "validateDateReq";
            panelValDateReq.Controls.Add(valCustom);
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab รายการพัสดุ

        protected void LoadGridItem()
        {
            IList<PurchaseOrderInstallmentItemInfo> infoList = bllPoInstalmentItem.GetPurchaseOrderInstallmentItem(GetPoSeq());
            Grid_Item.DataSource = infoList;
            Grid_Item.MasterTableView.GroupByExpressions.Clear();
            GridGroupByExpression geExpense = new GridGroupByExpression(Grid_Item.Columns[0]);
            Grid_Item.MasterTableView.GroupByExpressions.Add(geExpense);
            Grid_Item.DataBind();
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                double exvat = 0;
                double vat = 0;
                double amount = 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                if (((Label)(dataBoundItem["ExVatAmount"].FindControl("lblExVatAmount"))).Text.Length > 0)
                {
                    exvat = double.Parse(((Label)(dataBoundItem["ExVatAmount"].FindControl("lblExVatAmount"))).Text);
                }
                if (((Label)(dataBoundItem["VatAmount"].FindControl("lblVatAmount"))).Text.Length > 0)
                {
                    vat = double.Parse(((Label)(dataBoundItem["VatAmount"].FindControl("lblVatAmount"))).Text);
                }
                if (((Label)(dataBoundItem["NetAmount"].FindControl("lblNetAmount"))).Text.Length > 0)
                {
                    amount = double.Parse(((Label)(dataBoundItem["NetAmount"].FindControl("lblNetAmount"))).Text);
                }

                totalExvat += exvat;
                totalVat += vat;
                totalAmount += amount;

                //if (!Object.Equals(target, null))
                //{
                //    if (!Object.Equals(this.TipItemDetail, null))
                //    {
                //        this.TipItemDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                //    }
                //}
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                ((Label)footer["ExVatAmount"].FindControl("lblTotalExVatAmount")).Text = totalExvat.ToString("###,###,##0.000");
                ((Label)footer["VatAmount"].FindControl("lblTotalVatAmount")).Text = totalVat.ToString("###,###,##0.000");
                ((Label)footer["NetAmount"].FindControl("lblTotalNetAmount")).Text = totalAmount.ToString("###,###,##0.000");
            }
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab คณะกรรมการ

        protected void LoadGridCommittee()
        {
            IList<PurchaseOrderCommitteeInfo> infoListPoCommittee = bllPoCommittee.GetPurchaseOrderCommitteeWithParent(GetPoSeq());
            Grid_Committee.DataSource = infoListPoCommittee;
            GridGroupByExpression geFunction = new GridGroupByExpression(Grid_Committee.Columns[2]);
            GridGroupByExpression geRefNo = new GridGroupByExpression(Grid_Committee.Columns[3]);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geFunction);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geRefNo);
            Grid_Committee.DataBind();
            cmdFac.GridCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
        }

        protected void LoadCommitteeFunction()
        {
            IList<MasterCommitteeFunctionInfo> infoList = bllComFunction.GetMasterCommitteeFunction();
            cbCommitteeFunction.DataSource = infoList;
            cbCommitteeFunction.DataBind();
        }

        protected void LoadCommitteePosition()
        {
            IList<MasterCommitteePositionInfo> infoList = bllComPosition.GetMasterCommitteePosition();
            cbCommitteePosition.DataSource = infoList;
            cbCommitteePosition.DataBind();
        }

        protected void Grid_Committee_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommittee();
        }

        protected void rblCommitteeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelInternal.Visible = (rblCommitteeType.SelectedValue == "1");
            panelExternal.Visible = (rblCommitteeType.SelectedValue == "2");
            LoadValidateCommittee();
        }

        protected void cbCommitteeInternalName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbCommitteeInternalName.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbCommitteeInternalName.Items[j].FindControl("tableCommmitteeInternalName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void ShowGrid_Committee_Click(object sender, EventArgs e)
        {
            LoadGridCommittee();
        }

        protected void Edit_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            cmdFac.SetPanelList(panelInternal, "Edit");
            cmdFac.SetPanelList(panelExternal, "Edit");
            LoadValidateCommittee();
        }

        protected void AddNew_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            LoadValidateCommittee();
            ClearCommittee();
        }

        protected void btnDelete_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderCommitteeInfo> infoList = new List<PurchaseOrderCommitteeInfo>();
            if (panelGrid_Committee.Visible)
            {
                foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
                {
                    PurchaseOrderCommitteeInfo info = new PurchaseOrderCommitteeInfo();
                    RecordInfo infoRecord = new RecordInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    info.DeleteReason = txtDeleteReason.Text;
                    infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                    infoRecord.Updated_when = DateTime.Now;
                    info.InfoRecord = infoRecord;
                    infoList.Add(info);
                }
            }
            else
            {
                PurchaseOrderCommitteeInfo info = new PurchaseOrderCommitteeInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(hdCommitteeSeq.Value);
                info.DeleteReason = txtDeleteReason.Text;
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPoCommittee.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridCommittee();
        }

        protected void Delete_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderCommitteeInfo> infoList = new List<PurchaseOrderCommitteeInfo>();
            if (panelGrid_Committee.Visible)
            {
                foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
                {
                    PurchaseOrderCommitteeInfo info = new PurchaseOrderCommitteeInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    infoList.Add(info);
                }
            }
            else
            {
                PurchaseOrderCommitteeInfo info = new PurchaseOrderCommitteeInfo();
                info.Seq = Convert.ToInt32(hdCommitteeSeq.Value);
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPoCommittee.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridCommittee();
        }

        protected void AddNewSave_Committee_Click(object sender, EventArgs e)
        {
            PurchaseOrderCommitteeInfo info = new PurchaseOrderCommitteeInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
            MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
            HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
            RecordInfo infoRecord = new RecordInfo();
            SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
            PurchaseOrderInfo infoPo = new PurchaseOrderInfo();

            infoPo.Seq = GetPoSeq();
            info.Ref_no = Convert.ToInt32(txtCommitteeRefno.Value);
            infoType.Seq = Convert.ToInt32(rblCommitteeType.SelectedValue);
            infoType.Name = (rblCommitteeType.SelectedItem.Text);
            infoPosition.Seq = Convert.ToInt32(cbCommitteePosition.SelectedValue);
            infoPosition.Name = cbCommitteePosition.SelectedItem.Text;
            infoFunction.Seq = Convert.ToInt32(cbCommitteeFunction.SelectedValue);
            infoFunction.Name = cbCommitteeFunction.SelectedItem.Text;
            if (infoType.Seq == 1) //บุคลากรภายใน
            {
                infoEmployee.Seq = Convert.ToInt32(cbCommitteeInternalName.SelectedValue);
            }
            else
            {
                info.Ex_name = txtCommitteeExternalName.Text;
                info.Ex_descr = txtCommitteeExternalDescr.Text;
            }
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoPo = infoPo;
            info.InfoType = infoType;
            info.InfoExployee = infoEmployee;
            info.InfoPosition = infoPosition;
            info.InfoFunction = infoFunction;
            info.InfoRecord = infoRecord;

            try
            {
                bllPoCommittee.Insert(info);
                LoadGridCommittee();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void EditSave_Committee_Click(object sender, EventArgs e)
        {
            PurchaseOrderCommitteeInfo info = new PurchaseOrderCommitteeInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
            MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
            HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
            RecordInfo infoRecord = new RecordInfo();
            SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
            info.Seq = Convert.ToInt32(hdCommitteeSeq.Value);
            info.Ref_no = Convert.ToInt32(txtCommitteeRefno.Value);
            infoType.Seq = Convert.ToInt32(rblCommitteeType.SelectedValue);
            infoType.Name = (rblCommitteeType.SelectedItem.Text);
            infoPosition.Seq = Convert.ToInt32(cbCommitteePosition.SelectedValue);
            infoPosition.Name = cbCommitteePosition.SelectedItem.Text;
            infoFunction.Seq = Convert.ToInt32(cbCommitteeFunction.SelectedValue);
            infoFunction.Name = cbCommitteeFunction.SelectedItem.Text;
            if (infoType.Seq == 1) //บุคลากรภายใน
            {
                infoEmployee.Seq = Convert.ToInt32(cbCommitteeInternalName.SelectedValue);
            }
            else
            {
                info.Ex_name = txtCommitteeExternalName.Text;
                info.Ex_descr = txtCommitteeExternalDescr.Text;
            }
            infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Updated_when = DateTime.Now;
            info.InfoType = infoType;
            info.InfoExployee = infoEmployee;
            info.InfoPosition = infoPosition;
            info.InfoFunction = infoFunction;
            info.InfoRecord = infoRecord;
            try
            {
                bllPoCommittee.Update(info);
                LoadGridCommittee();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void Cancel_Committee_Click(object sender, EventArgs e)
        {
            LoadEditCommittee(Convert.ToInt32(hdCommitteeSeq.Value));
        }

        protected void ClearCommittee()
        {
            txtCommitteeRefno.Text = "";
            rblCommitteeType.Items[0].Selected = true;
            rblCommitteeType.Items[1].Selected = false;
            panelInternal.Visible = true;
            panelExternal.Visible = false;
            cbCommitteeInternalName.SelectedIndex = -1;
            cbCommitteeInternalName.Text = "";
            txtCommitteeExternalName.Text = "";
            txtCommitteeExternalDescr.Text = "";
            cbCommitteePosition.SelectedIndex = -1;
            cbCommitteePosition.Text = "";
            cbCommitteeFunction.SelectedIndex = -1;
            cbCommitteeFunction.Text = "";
        }

        protected void LoadEditCommittee(int ComSeq)
        {
            PurchaseOrderCommitteeInfo info = bllPoCommittee.GetPurchaseOrderCommittee(ComSeq);
            txtCommitteeRefno.Text = info.Ref_no.ToString();
            lblCommitteeRefNo.Text = info.Ref_no.ToString();
            rblCommitteeType.SelectedValue = info.InfoType.Seq.ToString();
            if (info.InfoType.Seq == 1)
            {
                panelInternal.Visible = true;
                panelExternal.Visible = false;
                cbCommitteeInternalName.SelectedValue = info.InfoExployee.Seq.ToString();
                cbCommitteeInternalName.Text = info.InfoExployee.Name;
                lblCommitteeInternalName.Text = info.InfoExployee.Name;
            }
            else
            {
                panelInternal.Visible = false;
                panelExternal.Visible = true;
                txtCommitteeExternalName.Text = info.Ex_name;
                txtCommitteeExternalDescr.Text = info.Ex_descr;
            }

            cbCommitteePosition.SelectedValue = info.InfoPosition.Seq.ToString();
            cbCommitteeFunction.SelectedValue = info.InfoFunction.Seq.ToString();
            cmdFac.ViewCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            cmdFac.SetViewMode(panelInternal);
            cmdFac.SetPanelList(panelInternal, "View");
            cmdFac.SetViewMode(panelExternal);
            cmdFac.SetPanelList(panelExternal, "View");
        }

        protected void Grid_Committee_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Image image = (Image)dataBoundItem["Image"].FindControl("Image1");
                if (dataBoundItem["InfoRecord.InfoStatus.Status"].Text == "W")
                {
                    image.ImageUrl = "../Image/Grid/Update.gif";
                }
                else
                {
                    image.ImageUrl = "../Image/Grid/Cancel.gif";
                }
            }
        }

        protected void LoadValidateCommittee()
        {
            RequiredFieldValidator valCommitteeRefno = new RequiredFieldValidator();
            valCommitteeRefno.ID = "ValtxtCommitteeRefno";
            valCommitteeRefno.ControlToValidate = "txtCommitteeRefno";
            valCommitteeRefno.SetFocusOnError = true;
            valCommitteeRefno.Display = ValidatorDisplay.Dynamic;
            valCommitteeRefno.ErrorMessage = "* กรุณาระบุชุดที่ *";
            panelValtxtCommitteeRefno.Controls.Add(valCommitteeRefno);
            RequiredFieldValidator valCommitteeInternalName = new RequiredFieldValidator();
            valCommitteeInternalName.ID = "ValcbCommitteeInternalName";
            valCommitteeInternalName.ControlToValidate = "cbCommitteeInternalName";
            valCommitteeInternalName.SetFocusOnError = true;
            valCommitteeInternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeInternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValcbCommitteeInternalName.Controls.Add(valCommitteeInternalName);
            RequiredFieldValidator valCommitteeExternalName = new RequiredFieldValidator();
            valCommitteeExternalName.ID = "ValtxtCommitteeExternalName";
            valCommitteeExternalName.ControlToValidate = "txtCommitteeExternalName";
            valCommitteeExternalName.SetFocusOnError = true;
            valCommitteeExternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeExternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValtxtCommitteeExternalName.Controls.Add(valCommitteeExternalName);
            RequiredFieldValidator valCommitteePosition = new RequiredFieldValidator();
            valCommitteePosition.ID = "ValcbCommitteePosition";
            valCommitteePosition.ControlToValidate = "cbCommitteePosition";
            valCommitteePosition.SetFocusOnError = true;
            valCommitteePosition.Display = ValidatorDisplay.Dynamic;
            valCommitteePosition.ErrorMessage = "* กรุณาระบุตำแหน่งกรรมการ *";
            panelValcbCommitteePosition.Controls.Add(valCommitteePosition);
            RequiredFieldValidator valCommitteeFunction = new RequiredFieldValidator();
            valCommitteeFunction.ID = "ValcbCommitteeFunction";
            valCommitteeFunction.ControlToValidate = "cbCommitteeFunction";
            valCommitteeFunction.SetFocusOnError = true;
            valCommitteeFunction.Display = ValidatorDisplay.Dynamic;
            valCommitteeFunction.ErrorMessage = "* กรุณาระบุหน้าที่กรรมการ *";
            panelValcbCommitteeFunction.Controls.Add(valCommitteeFunction);
        }

        protected void OnAjaxUpdateCommittee(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipCommittee(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTipCommittee(string elementID, UpdatePanel panel)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Order_Committee_History.ascx");
            //((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Order_Committee_History)ctrl).GetBdSeq = new CallBackHandleReturnInt(GetBdSeq);
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab กำหนดการปรับ

        protected void LoadGridPenalty()
        {
            IList<PurchaseOrderPenaltyInfo> infoList = bllPoPenalty.GetPurchaseOrderPenaltyWithParent(GetPoSeq());
            Grid_Penalty.DataSource = infoList;
            Grid_Penalty.DataBind();
            cmdFac.GridCommand(panelList_Penalty, panelGrid_Penalty, panelCommand_Penalty);
        }

        protected void LoadPenaltyCount()
        {
            IList<SysPenaltyCountInfo> info = bllPenaltyCount.GetSysPenaltyCount();
            cbPenaltyCount.DataSource = info;
            cbPenaltyCount.DataBind();
        }

        protected void LoadPenaltyRateType()
        {
            IList<SysPenaltyRateTypeInfo> info = bllPenaltyRateType.SysPenaltyRateType();
            cbPenaltyRateType.DataSource = info;
            cbPenaltyRateType.DataBind();
        }

        protected void Grid_Penalty_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridPenalty();
        }

        protected void AddNew_Penalty_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Penalty, panelGrid_Penalty, panelCommand_Penalty);
            LoadValidatePenalty();
        }

        private void LoadValidatePenalty()
        {
            RequiredFieldValidator valPenaltyName = new RequiredFieldValidator();
            valPenaltyName.ID = "ValtxtPenaltyName";
            valPenaltyName.ControlToValidate = "txtPenaltyName";
            valPenaltyName.SetFocusOnError = true;
            valPenaltyName.Display = ValidatorDisplay.Dynamic;
            valPenaltyName.ErrorMessage = "* กรุณาระบุปรับเนื่องจาก *";
            panelValtxtPenaltyName.Controls.Add(valPenaltyName);

            RequiredFieldValidator valPenaltyRate = new RequiredFieldValidator();
            valPenaltyRate.ID = "ValtxtPenaltyRate";
            valPenaltyRate.ControlToValidate = "txtPenaltyRate";
            valPenaltyRate.SetFocusOnError = true;
            valPenaltyRate.Display = ValidatorDisplay.Dynamic;
            valPenaltyRate.ErrorMessage = "* กรุณาระบุอัตราค่าปรับ *";

            RequiredFieldValidator valPenaltyRateType = new RequiredFieldValidator();
            valPenaltyRateType.ID = "ValcbPenaltyRateType";
            valPenaltyRateType.ControlToValidate = "cbPenaltyRateType";
            valPenaltyRateType.SetFocusOnError = true;
            valPenaltyRateType.Display = ValidatorDisplay.Dynamic;
            valPenaltyRateType.ErrorMessage = "* กรุณาระบุหน่วยค่าปรับ *";

            RequiredFieldValidator valPenaltyCount = new RequiredFieldValidator();
            valPenaltyCount.ID = "ValcbPenaltyCount";
            valPenaltyCount.ControlToValidate = "cbPenaltyCount";
            valPenaltyCount.SetFocusOnError = true;
            valPenaltyCount.Display = ValidatorDisplay.Dynamic;
            valPenaltyCount.ErrorMessage = "* กรุณาระบุระยะเวลาค่าปรับ *";

            panelValPanaltyRate.Controls.Add(valPenaltyRate);
            panelValPanaltyRate.Controls.Add(valPenaltyRateType);
            panelValPanaltyRate.Controls.Add(valPenaltyCount);
        }

        protected void Edit_Penalty_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Penalty, panelGrid_Penalty, panelCommand_Penalty);
            cmdFac.SetPanelList(panelLeast, "Edit");
            LoadValidatePenalty();
        }

        protected void Delete_Penalty_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderPenaltyInfo> infoList = new List<PurchaseOrderPenaltyInfo>();
            foreach (GridDataItem data in Grid_Penalty.MasterTableView.GetSelectedItems())
            {
                PurchaseOrderPenaltyInfo info = new PurchaseOrderPenaltyInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPoPenalty.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridPenalty();
        }

        protected void AddNewSave_Penalty_Click(object sender, EventArgs e)
        {
            PurchaseOrderPenaltyInfo info = new PurchaseOrderPenaltyInfo();
            SysPenaltyRateTypeInfo infoSysPenaltyRateType = new SysPenaltyRateTypeInfo();
            SysPenaltyCountInfo infoPenaltyCount = new SysPenaltyCountInfo();
            PurchaseOrderInfo infoPurchaseOrder = new PurchaseOrderInfo();
            RecordInfo infoRecord = new RecordInfo();

            info.Name = txtPenaltyName.Text;
            info.Descr = txtPenaltyDescr.Text;
            info.Rate = Convert.ToDouble(txtPenaltyRate.Text);
            infoSysPenaltyRateType.Seq = Convert.ToInt32(cbPenaltyRateType.SelectedValue);
            infoPenaltyCount.Seq = Convert.ToInt32(cbPenaltyCount.SelectedValue);

            if (panelLeast.Visible && txtLeast.Text != "")
            {
                info.Least = Convert.ToDouble(txtLeast.Text);
            }

            infoPurchaseOrder.Seq = GetPoSeq();
            infoRecord.Created_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Created_when = DateTime.Now;

            info.InfoPenaltyRateType = infoSysPenaltyRateType;
            info.InfoPenaltyCount = infoPenaltyCount;
            info.InfoPurchaseOrder = infoPurchaseOrder;
            info.InfoRecord = infoRecord;
            
            try
            {
                bllPoPenalty.Insert(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            LoadGridPenalty();
        }

        protected void EditSave_Penalty_Click(object sender, EventArgs e)
        {
            PurchaseOrderPenaltyInfo info = new PurchaseOrderPenaltyInfo();
            SysPenaltyRateTypeInfo infoSysPenaltyRateType = new SysPenaltyRateTypeInfo();
            SysPenaltyCountInfo infoPenaltyCount = new SysPenaltyCountInfo();
            PurchaseOrderInfo infoPurchaseOrder = new PurchaseOrderInfo();
            RecordInfo infoRecord = new RecordInfo();
            info.Seq = Convert.ToInt32(hdPenaltySeq.Value);
            info.Name = txtPenaltyName.Text;
            info.Descr = txtPenaltyDescr.Text;
            info.Rate = Convert.ToDouble(txtPenaltyRate.Text);
            infoSysPenaltyRateType.Seq = Convert.ToInt32(cbPenaltyRateType.SelectedValue);
            infoPenaltyCount.Seq = Convert.ToInt32(cbPenaltyCount.SelectedValue);

            if (panelLeast.Visible && txtLeast.Text != "")
            {
                info.Least = Convert.ToDouble(txtLeast.Text);
            }

            infoRecord.Updated_by = 1;
            infoRecord.Updated_when = DateTime.Now;

            info.InfoPenaltyRateType = infoSysPenaltyRateType;
            info.InfoPenaltyCount = infoPenaltyCount;
            info.InfoRecord = infoRecord;

            try
            {
                bllPoPenalty.Update(info);
                LoadGridPenalty();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void Cancel_Penalty_Click(object sender, EventArgs e)
        {
            LoadEditPenalty(Convert.ToInt32(hdPenaltySeq.Value));
        }

        protected void ShowGrid_Penalty_Click(object sender, EventArgs e)
        {
            LoadGridPenalty();
        }

        protected void LoadEditPenalty(int pen_seq)
        {
            PurchaseOrderPenaltyInfo info = bllPoPenalty.GetPurchaseOrderPenalty(pen_seq);

            hdPenaltySeq.Value = info.Seq.ToString();
            txtPenaltyName.Text = info.Name;
            txtPenaltyDescr.Text = info.Descr;
            txtPenaltyRate.Text = info.Rate.ToString();
            cbPenaltyRateType.SelectedValue = info.InfoPenaltyRateType.Seq.ToString();
            cbPenaltyCount.SelectedValue = info.InfoPenaltyCount.Seq.ToString();
            if (info.Least != null)
            {
                txtLeast.Text = info.Least.ToString();
                panelLeast.Attributes.Add("style", "visibility:visible");
            }
            else
            {
                panelLeast.Attributes.Add("style", "visibility:hidden");
            }
            
            cmdFac.ViewCommand(panelList_Penalty, panelGrid_Penalty, panelCommand_Penalty);
            cmdFac.SetViewMode(panelLeast);
            cmdFac.SetPanelList(panelLeast, "View");
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab เอกสารแนบ

        protected void LoadGridFile()
        {
            Grid_File.DataSource = bllPoFile.GetDocument(GetPoSeq(), "ICM_PURCHASE_ORDER_FILE", "ICM_PO_SEQ", "ICM_PO_FILE_SEQ");
            Grid_File.DataBind();

            cmdFac.GridCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void ShowGrid_File_Click(object sender, EventArgs e)
        {
            LoadGridFile();
        }

        protected void AddNew_File_Click(object sender, EventArgs e)
        {
            RequiredFieldValidator valFileName = new RequiredFieldValidator();
            valFileName.ID = "ValtxtFileName";
            valFileName.ControlToValidate = "txtFileName";
            valFileName.SetFocusOnError = true;
            valFileName.Display = ValidatorDisplay.Dynamic;
            valFileName.ErrorMessage = "* กรุณาระบุชื่อไฟล์ *";
            panelValtxtFileName.Controls.Add(valFileName);
            RequiredFieldValidator valAttachment = new RequiredFieldValidator();
            valAttachment.ID = "Valattachment";
            valAttachment.ControlToValidate = "attachment";
            valAttachment.SetFocusOnError = true;
            valAttachment.Display = ValidatorDisplay.Dynamic;
            valAttachment.ErrorMessage = "* กรุณาระบุที่อยู่ไฟล์ *";
            panelValattachment.Controls.Add(valAttachment);
            cmdFac.AddNewCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void AddNewSave_File_Click(object sender, EventArgs e)
        {
            FileInfo infoFile = new FileInfo(hdSourceFile.Value);
            DocumentInfo info = new DocumentInfo();
            RecordInfo infoRecord = new RecordInfo();
            infoRecord.Created_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Created_when = DateTime.Now;
            info.File_info = infoFile;
            info.Name = txtFileName.Text;
            info.Dest_path = hdSourceFile.Value;
            info.InfoRecord = infoRecord;

            try
            {
                bllPoFile.InsertFileToDB(info, "ICM_PURCHASE_ORDER_FILE", "ICM_PO_SEQ", GetPoSeq());
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            LoadGridFile();
        }

        protected void Delete_File_Click(object sender, EventArgs e)
        {
            IList<DocumentInfo> infoList = new List<DocumentInfo>();
            foreach (GridDataItem data in Grid_File.MasterTableView.GetSelectedItems())
            {
                DocumentInfo info = new DocumentInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPoFile.DeleteFileFromDB(infoList, "ICM_PURCHASE_ORDER_FILE", "ICM_PO_FILE_SEQ");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridFile();
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }

        protected void OnAjaxRequestFile(object sender, AjaxRequestEventArgs e)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Order_File_History.ascx");
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Order_File_History)ctrl).GetPoSeq = new CallBackHandleReturnInt(GetPoSeq);
            RadAjaxPanel2.Controls.Add(ctrl);
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab ข้อมูลรายงาน

        protected void LoadGrid_Report()
        {
            IList<SysReportInfo> infoList = bllReport.GetReportName("PO_APPROVE");
            Grid_Report.DataSource = infoList;
            Grid_Report.DataBind();
        }

        protected void Grid_Report_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGrid_Report();
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region ความคืบหน้า

        ProgressPurchaseOrderBLL bllPpo = new ProgressPurchaseOrderBLL();

        protected void LoadGridApprove()
        {
            IList<PurchaseOrderRouteInfo> InfoPprRouteList = bllPpo.GetPurchaseOrderApprove();
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridApprove");
            TmpGrid.DataSource = InfoPprRouteList;
            TmpGrid.DataBind();
        }

        protected void LoadGridInform()
        {
            IList<PurchaseOrderRouteInfo> InfoPprRouteList = bllPpo.GetPurchaseOrderInform();
            RadGrid TmpGrid2 = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridInform");
            GridGroupByExpression g;
            TmpGrid2.DataSource = InfoPprRouteList;
            TmpGrid2.MasterTableView.GroupByExpressions.Clear();
            g = new GridGroupByExpression(TmpGrid2.Columns[0]);
            TmpGrid2.MasterTableView.GroupByExpressions.Add(g);

            TmpGrid2.Columns[0].Visible = false;
            TmpGrid2.DataBind();
        }

        protected void LoadGridRequest()
        {
            IList<PurchaseOrderInfo> InfoPpr = bllPpo.GetPurchaseRequest();
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar2").FindControl("GridRequest");
            TmpGrid.DataSource = InfoPpr;
            TmpGrid.DataBind();
        }

        protected void LoadGridPublishing()
        {
            IList<BidInfo> InfoBid = bllPpo.GetBid();
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar3").FindControl("GridPublishing");
            TmpGrid.DataSource = InfoBid;
            TmpGrid.DataBind();
        }

        protected void LoadGridCommand()
        {
            IList<PurchaseOrderInfo> InfopurOrder = bllPpo.GetPurchaseOrder();
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar4").FindControl("GridCommand");
            TmpGrid.DataSource = InfopurOrder;
            TmpGrid.DataBind();
        }

        protected void LoadGridCheck()
        {
            IList<DeliveryNoteInfo> InfoDeliveryNote = bllPpo.GetDeliveryNote();
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar5").FindControl("GridCheck");
            TmpGrid.DataSource = InfoDeliveryNote;
            TmpGrid.DataBind();
        }

        protected void GridApprove_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridApprove();
        }

        protected void GridHistory_ItemCommand(object source, GridCommandEventArgs e)
        {
            //LoadGridApproveHistory();
        }

        protected void GridInformHis_ItemCommand(object source, GridCommandEventArgs e)
        {
            //LoadGridInformHistory();
        }

        protected void GridInform_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridInform();
        }

        protected void GridRequest_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridRequest();
        }

        protected void GridRequest_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":prr", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":prr", true);
                    }
                }
            }
        }

        protected void GridPublishing_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridPublishing();
        }

        protected void GridPublishing_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":br", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":br", true);
                    }
                }
            }
        }

        protected void GridCommand_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommand();
        }

        protected void GridCommand_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":por", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":por", true);
                    }
                }
            }
        }

        protected void GridCheck_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCheck();
        }

        protected void GridCheck_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":dnr", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":dnr", true);
                    }
                }
            }
        }

        protected void OnAjaxUpdate_AppDet(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_AppDet(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_AppDet(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            //if (all_value[0] == "Item")
            //{
            //    Session["Resource_Item_Id"] = all_value[1];
            //    Session["Expense_Id"] = null;
            //}
            //else
            //{
            //    Session["Resource_Item_Id"] = null;
            //    Session["Expense_Id"] = all_value[1];
            //}
            Session["RefNo"] = all_value[1];
            Session["DisType"] = all_value[2];
            Control ctrl = Page.LoadControl("../UserControl/TIP_Approve_Detail.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdate_TipHistoryApprove(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_TipHistoryApprove(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_TipHistoryApprove(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["HisSeq"] = all_value[1];
            Control ctrl;
            if (all_value[0] == "HisApprove")
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryApprove.ascx");
            }
            else
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryInform.ascx");
            }
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdate_TipHistoryInform(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_TipHistoryInform(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_TipHistoryInform(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["HisSeq"] = all_value[1];
            Control ctrl;
            if (all_value[0] == "HisApprove")
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryApprove.ascx");
            }
            else
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryInform.ascx");
            }
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void btnHistory_Click(object sender, EventArgs e)
        {

        }

        protected void btnHistory2_Click(object sender, EventArgs e)
        {

        }

        #endregion

    }
}
